package com.seed.uaa.login.impl;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.query.QueryChain;
import com.seed.application.Sa;
import com.seed.core.pojo.Account;
import com.seed.core.pojo.LoginDTO;
import com.seed.uaa.login.Login;
import com.seed.uaa.tenant.web.Tenant;
import com.seed.uaa.util.LoginCheckUtil;
import com.seed.uaa.web.organization.Organization;

import static com.seed.uaa.tenant.web.table.TenantTableDef.TENANT;
import static com.seed.uaa.web.organization.table.OrganizationTableDef.ORGANIZATION;

public class TenantUserUsernameLogin implements Login {

    @Override
    public void login(Account account, LoginDTO dto) {
        String tenantname = account.getTenantname();
        Tenant tenant = QueryChain.of(Tenant.class)
                .where(TENANT.TENANTNAME.eq(tenantname))
                .one();
        checkTenantLogin(tenant);

        String dataSourceKey = Sa.getDataSourceKey(tenantname);
        DataSourceKey.use(dataSourceKey, () -> {
            // TODO
        });
    }

    private void checkTenantLogin(Tenant tenant) {
        LoginCheckUtil.checkLogin(tenant);

        String organizationId = tenant.getOrganizationId();
        if(StrUtil.isNotBlank(organizationId)) {
            Organization organization = QueryChain.of(Organization.class)
                    .where(ORGANIZATION.ID.eq(organizationId))
                    .one();
            LoginCheckUtil.checkLogin(organization);
            checkAncestorLogin(organization);
        }
    }

    private void checkAncestorLogin(Organization organization) {
        String parentId = organization.getParentId();
        while (StrUtil.isNotBlank(parentId)) {
            organization = QueryChain.of(Organization.class)
                    .where(ORGANIZATION.ID.eq(parentId))
                    .one();
            LoginCheckUtil.checkAncestorLogin(organization);
            parentId = organization.getParentId();
        }
    }
}
